package www.bw.com.shiro.realms;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;


public class MyRealm  extends AuthorizingRealm{
    //返回权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //根据用户的账号查询具有的权限和角色，封装到SimpleAuthorizationInfo，返回
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();


        //去数据库根据账号查询角色和权限信息
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        roles.add("stu");
        Set<String> permissions = new HashSet<>();
        permissions.add("user:*");
        permissions.add("stu:delete");
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }


    //返回认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //info实际就是根据账号把数据库中的密码查询出来，封装起来了
        SimpleAuthenticationInfo info = null;
//        UsernamePasswordToken token1 = (UsernamePasswordToken)token;
//        token1.getUsername();
        String username = (String)token.getPrincipal();

        //如果账号不存在
        if(!"zhang".equals(username)){
            throw  new UnknownAccountException("账号不存在");
        }

        //去数据库查询密码
        String password = "d1bd80b9c45efe35c72e75bbb65845ce";
        info = new SimpleAuthenticationInfo(username,password,getName());
        info.setCredentialsSalt(ByteSource.Util.bytes("1234")); //设置盐值
        return info;
    }

    @Override
    public String getName() {
        return "自定义Realm";
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("12345","1234",1024);
        System.out.println(md5Hash.toString());
//        SimpleHash hash = new SimpleHash("md5","12345","1234",1024);
//        System.out.println(hash.toString());
    }
}
